#!/usr/bin/env python
#-*- encoding: utf8 -*-
import sys
import os
import commands
import time
import shutil

class buildDeb:
    def __init__(self):
        self.pkgname='kidux-emesene-plugin'
        self.maintainer='Tiago <tiago@kidux.net>'
        self.dist='unstable'
        self.mainversion='0.1'
        self.key='A8E8DE09'
        self.builddir = os.path.realpath(os.curdir)
        self.changefile = self.builddir+'/debian/changelog'
        self.filename=''
        print self.builddir
        self.updateChangelog()
#        self.build()
        self.deploy()


    def updateChangelog(self):
        os.system('svn update')
        a = commands.getoutput('svn log -r COMMITTED').split('\n')
        a.remove(a[0])
        a.remove(a[-1])
        version =a[0].split(' ')[0].replace('r', self.mainversion+'svn')
        self.filename = self.pkgname+'_'+version
        a.remove(a[0])
        changes = ''
        temptime = time.ctime().split(" ")
        weekday = temptime[0]
        month = temptime[1]
        day = temptime[2]
        now = temptime[3]
        year = temptime[4]
        #TODO: Recuperar TIMEZONE do sistema
        timestring=weekday+', '+day+' '+month+' '+year+' '+now+' -0300'
        for i in a:
            if i != '':
                changes = changes+' * '+i+'\n'
        changestring=self.pkgname+' ('+version+') '+self.dist+'; urgency=low\n\n'+changes+'\n -- '+self.maintainer+' '+timestring
        if os.path.exists(self.changefile):
            f = open(self.changefile)
            changelog = changestring+'\n\n'+f.read()
            f.close()
        else:
            changelog = changestring
        print changelog

        f = open(self.changefile,'w')
        f.write(changelog)
        f.close()

    def build(self):
        shutil.rmtree(self.builddir+'/dist/')
        os.mkdir(self.builddir+'/dist/')
        os.system('python setup.py bdist')
        os.chdir(self.builddir+'/dist/')
        os.system('tar xvzf '+os.listdir(os.curdir)[0])

    def deploy(self):
        os.chdir(self.builddir)
        os.system(' dpkg-buildpackage -sgpg -k'+self.key+' -I/.svn')
        os.system('scp ../'+self.filename+'* kidux.net:/opt/incoming')
        os.system('rm -f ../'+self.filename+'*')


builddeb = buildDeb()
